package org.example.xsda.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.xsda.entity.*;
import org.example.xsda.mapper.*;
import org.example.xsda.vo.StatisticsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 统计服务
 */
@Slf4j
@Service
public class StatisticsService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClassesMapper classesMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private StudentScoreMapper studentScoreMapper;

    @Autowired
    private RedisService redisService;

    // 缓存key
    private static final String CACHE_KEY_STATISTICS = "statistics:data";

    /**
     * 获取系统统计数据（带缓存）
     */
    public StatisticsVO getStatistics() {
        try {
            // 先从缓存中获取
            Object cached = redisService.get(CACHE_KEY_STATISTICS);
            if (cached != null) {
                log.debug("从缓存中获取统计数据");
                return (StatisticsVO) cached;
            }
        } catch (Exception e) {
            log.warn("获取缓存失败，直接查询数据库：{}", e.getMessage());
        }
        
        // 缓存未命中，从数据库查询
        StatisticsVO vo = new StatisticsVO();

        // 总数统计
        vo.setTotalStudents(studentMapper.selectCount(null));
        vo.setTotalClasses(classesMapper.selectCount(null));
        vo.setTotalDepts(deptMapper.selectCount(null));
        vo.setTotalScores(studentScoreMapper.selectCount(null));

        // 按院系统计学生数
        List<Student> allStudents = studentMapper.selectList(null);
        Map<Long, List<Student>> studentsByDeptMap = allStudents.stream()
                .collect(Collectors.groupingBy(Student::getDeptId));
        
        List<Map<String, Object>> studentsByDept = new ArrayList<>();
        List<Dept> depts = deptMapper.selectList(null);
        for (Dept dept : depts) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", dept.getDeptName());
            map.put("value", studentsByDeptMap.getOrDefault(dept.getId(), Collections.emptyList()).size());
            studentsByDept.add(map);
        }
        vo.setStudentsByDept(studentsByDept);

        // 按班级统计学生数（Top 10）
        Map<Long, List<Student>> studentsByClassMap = allStudents.stream()
                .collect(Collectors.groupingBy(Student::getClassId));
        
        List<Map<String, Object>> studentsByClass = new ArrayList<>();
        List<Classes> classes = classesMapper.selectList(new LambdaQueryWrapper<Classes>().last("LIMIT 10"));
        for (Classes cls : classes) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", cls.getClassName());
            map.put("value", studentsByClassMap.getOrDefault(cls.getId(), Collections.emptyList()).size());
            studentsByClass.add(map);
        }
        vo.setStudentsByClass(studentsByClass);

        // 成绩分布统计
        List<StudentScore> allScores = studentScoreMapper.selectList(null);
        Map<String, Long> scoreDistribution = new HashMap<>();
        if (allScores != null && !allScores.isEmpty()) {
            scoreDistribution.put("优秀", allScores.stream()
                .filter(s -> s.getScore() != null && s.getScore().intValue() >= 90).count());
            scoreDistribution.put("良好", allScores.stream()
                .filter(s -> s.getScore() != null && s.getScore().intValue() >= 80 && s.getScore().intValue() < 90).count());
            scoreDistribution.put("及格", allScores.stream()
                .filter(s -> s.getScore() != null && s.getScore().intValue() >= 60 && s.getScore().intValue() < 80).count());
            scoreDistribution.put("不及格", allScores.stream()
                .filter(s -> s.getScore() != null && s.getScore().intValue() < 60).count());
        } else {
            scoreDistribution.put("优秀", 0L);
            scoreDistribution.put("良好", 0L);
            scoreDistribution.put("及格", 0L);
            scoreDistribution.put("不及格", 0L);
        }
        vo.setScoreDistribution(scoreDistribution);

        // 性别分布
        Map<String, Long> genderDistribution = new HashMap<>();
        if (allStudents != null && !allStudents.isEmpty()) {
            genderDistribution.put("男", allStudents.stream()
                .filter(s -> s.getGender() != null && s.getGender() == 1).count());
            genderDistribution.put("女", allStudents.stream()
                .filter(s -> s.getGender() != null && s.getGender() == 2).count());
        } else {
            genderDistribution.put("男", 0L);
            genderDistribution.put("女", 0L);
        }
        vo.setGenderDistribution(genderDistribution);

        // 存入缓存（5分钟，统计数据需要相对实时）
        try {
            redisService.set(CACHE_KEY_STATISTICS, vo, 5, java.util.concurrent.TimeUnit.MINUTES);
            log.debug("将统计数据存入缓存");
        } catch (Exception e) {
            log.warn("缓存统计数据失败：{}", e.getMessage());
        }

        return vo;
    }
    
    /**
     * 清除统计数据缓存（在数据变更时调用）
     */
    public void clearStatisticsCache() {
        redisService.delete(CACHE_KEY_STATISTICS);
        log.debug("清除统计数据缓存");
    }
}

